import 'package:aliplayer_widget/utils/log_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:yyshort/common/apis/user_api.dart';
import 'package:yyshort/common/model/useInfo_model.dart';
import 'package:yyshort/common/routers/names.dart';
import 'package:yyshort/common/utils/alert_dialog_utils.dart';
import 'package:yyshort/common/values/colors.dart';
import 'package:yyshort/common/values/shadows.dart';
import 'package:yyshort/common/widgets/app.dart';
import 'package:yyshort/common/widgets/widgets.dart';
import 'package:yyshort/pages/favorite_list/index.dart';
import 'package:yyshort/pages/login/view.dart';
import 'package:yyshort/pages/payment/TempWidget.dart';
import 'package:yyshort/pages/personal/about_us_page.dart';
import 'package:yyshort/pages/personal/feedback_page.dart';
import 'index.dart';

class PersonalPage extends GetView<PersonalController>
    with WidgetsBindingObserver {
  const PersonalPage({super.key});
  @override
  Widget build(BuildContext context) {
    // 页面构建时刷新用户信息
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   controller.fetchUserInfo();
    // });
    return Scaffold(
      backgroundColor: Colors.black,
      body: Obx(
        // 外层Obx确保整个页面能响应状态变化
        () => SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 20),
            child: Column(
              children: [
                _buildLogo(),
                SizedBox(height: 20),
                _buildMiddleSection(),
                SizedBox(height: 20),
                _buildBottomList(), // 调用修复后的列表构建方法
                SizedBox(height: 20),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // Center(
  //             child: GestureDetector(
  //               child: Text(
  //                 '反馈'.tr,
  //                 style: TextStyle(color: Colors.amber[300], fontSize: 18),
  //               ),
  //               onTap: () {
  //                 Get.to(
  //                   LanguageSelectionPage(),
  //                   // // 使用淡入淡出动画，减少视觉跳动
  //                   // transition: Transition.fade,
  //                   // 缩短动画时长
  //                   duration: const Duration(milliseconds: 250),
  //                   // 确保背景色过渡平滑
  //                   opaque: false,
  //                 );
  //               },
  //             ),
  //           ),

  Widget _buildLogo() {
    bool hasVip = UserInfo().vipExpireTime.isNotEmpty;
    return Container(
      margin: EdgeInsets.only(top: (40 + 20.0)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            height: 76,
            width: 76,
            margin: EdgeInsets.symmetric(horizontal: 0),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    // ignore: deprecated_member_use
                    color: Colors.grey.withOpacity(0.5),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: const Offset(0, 3),
                  ),
                ],
                borderRadius: BorderRadius.all(Radius.circular(76 * 0.5)),
              ),
              child: Center(
                child: GestureDetector(
                  // 添加点击事件
                  onTap: () async {
                    // 点击图片后执行的操作
                    print("Logo图片被点击了");
                    // 可以在这里添加导航、弹窗或其他业务逻辑
                    // var result = await Get.toNamed(AppRoutes.yylogin);
                    // // 如果返回true，则触发刷新
                    // if (result == true) {
                    //   controller.onReady(); // 调用刷新数据的方法
                    // }

                    if (UserInfo().loginType == 0) {
                      Get.toNamed(AppRoutes.YyLogin)?.then((_) {
                        controller.onReady();
                      });
                    }
                  },

                  child: UserInfo().avatar.isNotEmpty
                      ? ClipOval(
                          child: CachedNetworkImage(
                            imageUrl: UserInfo().avatar,
                            fit: BoxFit.cover,
                            errorListener: (value) {
                              ClipOval(
                                child: Image.asset(
                                  "assets/images/default_avatar.png",
                                  fit: BoxFit.cover,
                                ),
                              );
                            },
                          ),
                        )
                      : ClipOval(
                          child: Image.asset(
                            "assets/images/default_avatar.png",
                            fit: BoxFit.cover,
                          ),
                        ),
                ),
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 15),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  UserInfo().nickname,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontFamily: "Montserrat",
                    fontWeight: FontWeight.w600,
                    fontSize: 24,
                    height: 1,
                  ),
                ),
                if (hasVip)
                  Padding(
                    padding: const EdgeInsets.only(left: 5),
                    child: Image.asset("assets/images/vip.png", height: 20),
                  ),
              ],
            ),
          ),
          SizedBox(height: 5),
          hasVip
              ? Text(
                  "${'到期时间'.tr}：${UserInfo().vipExpireTime}",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Color(0xFF999999),
                    fontFamily: "Avenir",
                    fontWeight: FontWeight.w400,
                    fontSize: 16,
                    height: 1,
                  ),
                )
              : SizedBox(),
        ],
      ),
    );
  }

  Widget _buildMiddleSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 29 / 2),
      decoration: BoxDecoration(
        color: Color(0xFF1C1C1E),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "当前硬币".tr,
                    style: TextStyle(
                      fontFamily: "PingFangSC",
                      fontSize: 32 / 2,
                      color: Colors.white,
                    ),
                  ),
                  Text(
                    UserInfo().coin.toString(),
                    style: TextStyle(
                      fontFamily: "FuturaLTPro",
                      fontSize: 66 / 2,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: const EdgeInsets.only(right: 14),
              constraints: const BoxConstraints(minWidth: 88),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFFFFF8DEA5), Color(0xFFFFF4D288)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(16),
              ),
              child: ElevatedButton(
                onPressed: () {
                  // Get.to( TempWidget());//demo

                  Get.toNamed(AppRoutes.Payment);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.transparent,
                  shadowColor: Colors.transparent,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                ),
                child: Text('获取更多'.tr, style: TextStyle(color: Colors.black)),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomList() {
    // 关键修复：将列表数据放在Obx内部，确保语言变化时重新生成
    return Obx(() {
      // 每次重建时根据当前语言重新生成列表（关键）
      List<Map<String, String>> temp = [
        {"Watchlist": '收藏列表'.tr},
        {"Language": '语言选择'.tr},
        {"Feedback": '反馈'.tr},
        {"RechargeRecords": "消费记录".tr},
        {"AutoPurchase": "自动解锁".tr},
        {"Privacy": "关于我们".tr},
        if (UserInfo().loginType != 0) {"LogOut": '退出登录'.tr},
        if (UserInfo().loginType != 0) {"AccountDeletion": '注销账号'.tr},
      ];

      logd('---------------------');
      logd(UserInfo().isAutoBuy);
      logd('---------------------');

      return Container(
        decoration: BoxDecoration(
          color: Color(0xFF1C1C1E),
          borderRadius: BorderRadius.circular(10),
        ),
        margin: EdgeInsets.symmetric(horizontal: 29 / 2),
        padding: EdgeInsets.symmetric(vertical: 0),
        child: ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          itemCount: temp.length,
          itemBuilder: (context, index) {
            final itemKey = temp[index].keys.first;
            final itemValue = temp[index].values.first;

            return ListTile(
              onTap: () => itemKey != "AutoPurchase"
                  ? controller.junpToNextPage(context, index)
                  : null,
              leading: Image.asset(
                "assets/images/$itemKey.png",
                width: 24,
                height: 24,
              ),
              title: Text(itemValue, style: TextStyle(color: Colors.white)),
              trailing: itemKey == "AutoPurchase"
                  ? Switch(
                      value: UserInfo().isAutoBuy == 1 ? true : false,
                      onChanged: (value) {
                        controller.setAutoBuyEnabled(value);
                      },
                      activeColor: Colors.orange[300],
                      inactiveThumbColor: Colors.grey,
                    )
                  : Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.white,
                      size: 14,
                    ),
              contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 0),
              minVerticalPadding: 0,
            );
          },
        ),
      );
    });
  }
}
